package dk.liljedahl.christian.apx.shipdaemon;

import javax.script.*;

public class ExpressionParser {
	// See http://java.sun.com/developer/technicalArticles/J2SE/Desktop/scripting/
	
	public String error = "";
	public void evaluateEventScript(){
				
		error = "";
		ScriptEngineManager mgr = new ScriptEngineManager();
		  ScriptEngine jsEngine = mgr.getEngineByName("ECMAScript");
		  try {
			jsEngine.put("analog", analog);
			jsEngine.put("pinmode", pinmode);
			jsEngine.put("digital", digital);
			jsEngine.put("digitalwrite", digitalwrite);
			jsEngine.put("analogwrite", analogwrite);			
			jsEngine.put("condition", condition);
			jsEngine.put("status", status);  // Presence status - status[0] 
			jsEngine.put("message", message);
			jsEngine.put("messagerecipients", messagerecipients);
			jsEngine.put("scriptmemory_int", scriptmemory_int);

		    jsEngine.eval(script);
		    
		  } catch (ScriptException ex) {
			  error = "Parsing failed.";
		  }    		
	}

	
	public void evaluateResponseScript(){
		error = "";
		// THis is used for the responses
		ScriptEngineManager mgr = new ScriptEngineManager();
		  ScriptEngine jsEngine = mgr.getEngineByName("ECMAScript");
		  try {
			jsEngine.put("analog", analog);
			jsEngine.put("digital", digital);
			jsEngine.put("digitalwrite", digitalwrite);
			jsEngine.put("analogwrite", analogwrite);

			jsEngine.put("status", status);  // status[0] 
			jsEngine.put("incoming", incoming);
			jsEngine.put("incomingname", incomingname);
			jsEngine.put("response", response);
			jsEngine.put("scriptmemory_int", scriptmemory_int);

		    jsEngine.eval(script);
		    
		  } catch (ScriptException ex) {
			  error = "Parsing failed.";
		  }    		
	}
	
	public void setAllParametersToDummyValues(){
		for(int i=0;i<30;i++){
			digital[i] = 0;
			digitalwrite[i] = 0;
			analog[i] = 0;
			analogwrite[i] = 0;
			pinmode[i] = 0;
			condition[i] = false;
			message[i] = "";
			messagerecipients[i] = "";
			scriptmemory_int[i] = 0;
		}
		incoming = "";
		incomingname[0] = "";
		response[0] = "";
		status[0] = "";		
	}

	public int[] digital = new int[30];
	public int[] digitalwrite = new int[30];
	public int[] analogwrite = new int[30]; // Think about if we need to limit to certain ports, the pwm ports
	public int[] pinmode = new int[30]; // 0: INPUT, 1:OUTPUT
	public int[] analog = new int[30];
	public boolean[] condition = new boolean[30];
	public String[] message = new String[30];
	public String[] messagerecipients = new String[30];
	public String script;

	public int[] scriptmemory_int = new int[30]; // Used to make the script able to remember data from run to run
	
	// Some for Response Script handling
	public String incoming;
	public String[] incomingname = new String[1];
	public String[] response = new String[1];
	
	// String for presence status
	public String[] status = new String[1];

}
